//
//  UIView+UIViewController.m
//  05 Responder
//
//  Created by wei.chen on 14-8-23.
//  Copyright (c) 2014年 www.iphonetrain.com 无限互联3G学院. All rights reserved.
//

#import "UIView+UIViewController.h"
#import <objc/runtime.h>

@implementation UIView (UIViewController)


+ (void)load
{
    Method setAlignmentRectInsets = class_getInstanceMethod(self, @selector(alignmentRectInsets));
    Method zm_setAlignmentRectInsets = class_getInstanceMethod(self, @selector(zm_alignmentRectInsets));
    
    // 交互方法
    method_exchangeImplementations(setAlignmentRectInsets, zm_setAlignmentRectInsets);
    
}



- (void)setAlignmentRectInsets:(UIEdgeInsets)edgeInsets
{
    
    NSValue *insetValue = [NSValue valueWithUIEdgeInsets:edgeInsets];

    objc_setAssociatedObject(self, @"alignmentRectInsets", insetValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC);


}



- (UIEdgeInsets)zm_alignmentRectInsets{
    
    NSValue *insetValue = objc_getAssociatedObject(self, @"alignmentRectInsets");
    
    
    if (insetValue) {

        return [insetValue UIEdgeInsetsValue];

    } else {
        
        return [self zm_alignmentRectInsets];
    }


}




- (UIViewController *)viewController {
    
    //通过响应者链，取得此视图所在的视图控制器
    UIResponder *next = self.nextResponder;
    do {
        
        //判断响应者对象是否是视图控制器类型
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        
        next = next.nextResponder;
        
    }while(next != nil);
    
    return nil;
}

@end
